package com.yx.cloud.activity;

import static com.iot.common.utils.Event.MESSAGE_TYPE_REQUEST_MAP_AND_PATH;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.aliyun.aligeniessp_1_0.models.ListDeviceByUserIdResponseBody;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.iot.base.service.req.DataBag;
import com.iot.base.service.req.DataParam;
import com.iot.common.utils.Event;
import com.iot.common.utils.LogUtils;
import com.iot.product.sweeper.bean.Robot;
import com.iot.product.sweeper.bean.RobotStatus;
import com.iot.sdk.yugong.YuGongConstants;
import com.iot.sdk.yugong.resp.YuGongRespData;
import com.iot.sweeper.AppContext;
import com.yx.cloud.Interface.OnItemClickListener;
import com.yx.cloud.MyApplication;
import com.yx.cloud.R;
import com.yx.cloud.adapter.MainAdapter;
import com.yx.cloud.adapter.MainAddAdapter;
import com.yx.cloud.adapter.MainMesListAdapte;
import com.yx.cloud.base.BaseActivity;
import com.yx.cloud.base.LazyLoadFragment;
import com.yx.cloud.bean.MainMesListBean;
import com.yx.cloud.bean.RobotIconColorBean;
import com.yx.cloud.constant.Constants;
import com.yx.cloud.databinding.ActivityMainBinding;
import com.yx.cloud.fragment.BaseStationFragment;
import com.yx.cloud.fragment.MainFragment;
import com.yx.cloud.fragment.MenuRightFragment;
import com.yx.cloud.product.ProductConfigConstants;
import com.yx.cloud.utils.AliHttpRequest_Runnable;
import com.yx.cloud.utils.AppUtil;
import com.yx.cloud.utils.Intent_utils;
import com.yx.cloud.utils.RomUtils;
import com.yx.cloud.utils.SharedPreferencesList;
import com.yx.cloud.utils.SharedPrefsUtil;
import com.yx.cloud.utils.StatusBarColorUtils;
import com.yx.cloud.utils.ThreadUtils;
import com.yx.cloud.utils.ToastUtil;
import com.yx.cloud.view.BottomSettingView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class MainActivity2 extends BaseActivity implements /*GestureDetector.OnGestureListener, View.OnTouchListener,*/ View.OnClickListener {
    private final static String TAG = "MainActivity";
    private static final int MSG_KEEP_ALIVE = -1;
    private static final int FLING_MIN_DISTANCE = 50;
    private static final int FLING_MIN_DISTANCE_TOUCH = 350;
    private static final int FLING_MIN_VELOCITY = 0;
    private static boolean remindUpdate = false;
    public List<MainMesListBean> mMesListData;
    public MainMesListAdapte mesAdapte;
    public GestureDetector mGestureDetector;
    public ActivityMainBinding binding;
    public Dialog dialog, firmware_dialog;
    public MyApplication application;
    public int AligenieUserInfo = 0, authentication = 0, tmallDeviceList = 0, getTuyaDevice = 0, authorized = 0;
    public AliHttpRequest_Runnable runnable;
    public boolean isMianShow = true;
    public MainFragment mainFragment;
    BaseStationFragment bf;
    private List<Fragment> mainfragmentList;
    private MainAdapter mainAdapter;
    private VelocityTracker mVelocityTracker;
    private Robot deviceBean;
    private List<Robot> newDeviceList;
    private PopupWindow popupWindow;
    private RecyclerView popuListView;
    private GridLayoutManager layoutManager;
    private MainAddAdapter mAddAdapter;
    private float ee1 = 0, ee2 = 0, yVelocity;
    private FragmentManager fm;
    private boolean islockScreen = false, isX5Device = false, sing = false;
    private List<ListDeviceByUserIdResponseBody.ListDeviceByUserIdResponseBodyResult> result;
    private int regFrom, currentItem, startX, criticalValue = 50;
    private Handler myHandler;
    private MainFragmentHandler handler;

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onCreate() {
        Log.i(TAG, "---------------- bottomLayoutView     oncreate : ");
        StatusBarColorUtils.fullScreen(this);//导航栏变透明了
        application = (MyApplication) this.getApplicationContext();
        handler = new MainFragmentHandler(this);
        //  LanguageUtils.getAndsetLanguage(this,"main");
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        runnable = new AliHttpRequest_Runnable();
        initData();
        // isScreenPOWER();//监听系统休眠或锁屏
        myHandler = new MainActivity2.MainHandler(this);
        myHandler.sendEmptyMessage(MESSAGE_TYPE_REQUEST_MAP_AND_PATH);
        myHandler.sendEmptyMessage(MSG_KEEP_ALIVE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //TODO 需要取消注册
        if (!EventBus.getDefault().isRegistered(this)) {//加上判断
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        application = (MyApplication) this.getApplicationContext();
        if (islockScreen) {
            //判断是否息屏后再打开
            islockScreen = false;
//            AppContext.get().setDeviceVariety("default");
        }
        //是否有新消息
        AppContext.getAccountService().hasNewNotification(null);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initData() {
        mVelocityTracker = VelocityTracker.obtain();
        binding.mMainViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                // Log.i(TAG, "  ---onPageScrolled------------------------ main_isShow : " + position);
            }

            @Override
            public void onPageSelected(int position) {
                //Log.i(TAG, "  ---onPageSelected----------------------dddddddddddddddd-------: " + position);
                setCurrentPage(position);
                setPageSelectStateChange(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                //“0”表示什么都不做，“1”表示开始滑动，“2”表示结束滑动。
                switch (state) {
                    case 1:
                        Log.i(TAG, currentItem + " : ---onPageScrollStateChanged----000000000000-----: " + state);
                        mainFragment.bottomLayoutView.mTvPreferences.setClickable(false);//设置偏好
                        mainFragment.bottomLayoutView.mCbMainBottomUnfold.setClickable(false);//滑动时上拉不可点击
                        isMianShow = true;
                        break;
                    case 2:
                        break;
                    case 0:
                        currentItem = binding.mMainViewPager.getCurrentItem();
                        //LogUtils.i(" currentItem >>>>>>>>>>>>>>>>>>>>>>  " + currentItem);
                        mainFragment.bottomLayoutView.mTvPreferences.setClickable(true);//设置偏好
                        mainFragment.bottomLayoutView.mCbMainBottomUnfold.setClickable(true);
                        break;
                }
            }
        });

        /**
         *主界面消息列表提醒
         */
        mMesListData = new ArrayList<>();
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        binding.mainMesList.setLayoutManager(layoutManager);
        mesAdapte = new MainMesListAdapte(MainActivity2.this, mMesListData);
        binding.mainMesList.setAdapter(mesAdapte);
        //删除主界面消息
        mesAdapte.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {

                ImageView megClose = view.findViewById(R.id.tv_messageClose);
                megClose.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (RomUtils.isFastClick()) {
                            return;
                        }
                        mMesListData.remove(position);
                        mesAdapte.notifyDataSetChanged();
                    }
                });
            }
        });

        binding.ivMainReturn.setOnClickListener(this);
        binding.ivRightMenu.setOnClickListener(this);
        binding.ivGreatManyIcon.setOnClickListener(this);

        fm = getSupportFragmentManager();
        mainHandleDeviceList();
    }


    @Override
    public void onClick(View v) {
        if (RomUtils.isFastClick()) {
            return;
        }
        int id = v.getId();
        if (id == R.id.iv_mainReturn) {
            MyApplication.recvActive = false;
            AppContext.get().disconnectDevice();
            Intent_utils.backIntent(this, MainBottomTabActivity.class);
        } else if (id == R.id.iv_rightMenu) {
            Intent_utils.enterIntent(this, MenuRightFragment.class);
        } else if (id == R.id.base_station_guide_layout01) {
            //引导界面1
            bf.baseStationGuideLayout01.setVisibility(View.INVISIBLE);
            bf.baseStationGuideLayout02.setVisibility(View.VISIBLE);
            bf.baseStationGuideLayout03.setVisibility(View.INVISIBLE);
            bf.baseStationGuideLayout04.setVisibility(View.INVISIBLE);
        } else if (id == R.id.base_station_guide_layout02) {
            //引导界面2
            bf.baseStationGuideLayout01.setVisibility(View.INVISIBLE);
            bf.baseStationGuideLayout02.setVisibility(View.INVISIBLE);
            bf.baseStationGuideLayout03.setVisibility(View.VISIBLE);
            bf.baseStationGuideLayout04.setVisibility(View.INVISIBLE);
        } else if (id == R.id.base_station_guide_layout03) {
            //引导界面3
            bf.baseStationGuideLayout01.setVisibility(View.INVISIBLE);
            bf.baseStationGuideLayout02.setVisibility(View.INVISIBLE);
            bf.baseStationGuideLayout03.setVisibility(View.INVISIBLE);
            bf.baseStationGuideLayout04.setVisibility(View.VISIBLE);
        } else if (id == R.id.base_station_guide_layout04) {
            //引导界面4
            bf.baseStationGuideLayout01.setVisibility(View.INVISIBLE);
            bf.baseStationGuideLayout02.setVisibility(View.INVISIBLE);
            bf.baseStationGuideLayout03.setVisibility(View.INVISIBLE);
            bf.baseStationGuideLayout04.setVisibility(View.INVISIBLE);
            bf.baseGuideDialog.dismiss();
        } else if (id == R.id.main_guide_layout01) {
            mainFragment.mainGuideLayout01.setVisibility(View.INVISIBLE);
            mainFragment.mainGuideLayout02.setVisibility(View.VISIBLE);
            mainFragment.mainGuideLayout03.setVisibility(View.INVISIBLE);
            mainFragment.mainGuideLayout04.setVisibility(View.INVISIBLE);
        } else if (id == R.id.main_guide_layout02) {
            mainFragment.mainGuideLayout01.setVisibility(View.INVISIBLE);
            mainFragment.mainGuideLayout02.setVisibility(View.INVISIBLE);
            mainFragment.mainGuideLayout03.setVisibility(View.VISIBLE);
            mainFragment.mainGuideLayout04.setVisibility(View.INVISIBLE);
        } else if (id == R.id.main_guide_layout03) {
            mainFragment.mainGuideLayout01.setVisibility(View.INVISIBLE);
            mainFragment.mainGuideLayout02.setVisibility(View.INVISIBLE);
            mainFragment.mainGuideLayout03.setVisibility(View.INVISIBLE);
            mainFragment.mainGuideLayout04.setVisibility(View.VISIBLE);
//            if (productConfig.optBoolean(ProductConfigConstants.hasMultiStyle)) {
//            } else {
//                mainFragment.mainGuideLayout04.setVisibility(View.GONE);
//                mainFragment.guideDialog.dismiss();
//            }
        } else if (id == R.id.main_guide_layout04) {
            Log.d(TAG, "MianGuide***************************44444 : ");
            mainFragment.mainGuideLayout01.setVisibility(View.INVISIBLE);
            mainFragment.mainGuideLayout02.setVisibility(View.INVISIBLE);
            mainFragment.mainGuideLayout03.setVisibility(View.INVISIBLE);
            mainFragment.mainGuideLayout04.setVisibility(View.INVISIBLE);
            mainFragment.guideDialog.dismiss();
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        switch (event.getType()) {
            case Event.MSG_ROBOT_STATE_HEALTH_POWER:
                if (AppContext.get().getCurrentDevice() != null) {
                    AppContext.get().getCurrentDevice().getMap().getSweeper().setIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.robot_inmap));
                    Log.d("setIcon", "set health power icon");
                }
                break;
            case Event.MSG_ROBOT_STATE_LOW_POWER:
                if (AppContext.get().getCurrentDevice() != null) {
                    AppContext.get().getCurrentDevice().getMap().getSweeper().setIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.robot_low_power));
                    Log.d("setIcon", "set low power icon");
                }
                break;
            case Event.MESSAGE_TYPE_SEND_UPGRADE_URL_TO_DEVICE:
                //获取固件包url
                if (event.isResult()) {
                    productConfig = AppContext.getConfig();
                    LogUtils.i("获取固件包 数据 " + remindUpdate + " , " + productConfig.optBoolean(ProductConfigConstants.canUpgradeFirmwareChannel));
                    if (remindUpdate) {
                        remindUpdate = false;
                        Robot connect_upgrade = AppContext.get().getCurrentDevice();
                        YuGongRespData content = (YuGongRespData) event.getContent();
                        List<YuGongRespData.FileListBean> file_list = content.getFile_list();
                        String url = file_list.get(0).getData_s3_url();
                        DataBag dataBag = new DataBag();
                        dataBag.setType(file_list.get(0).getData_name());
                        dataBag.setUrl(url);
                        dataBag.setVersion(connect_upgrade.getFirmwareUpdateInfo().getNewVersion());
                        dataBag.setFile_name(connect_upgrade.getFirmwareUpdateInfo().getFileName());
                        AppContext.getProductService().sendUpgradeUrlToDevice(dataBag);
                        if (productConfig.optBoolean(ProductConfigConstants.canUpgradeFirmwareChannel)) {
                            Intent_utils.enterIntentContext(this, GyroFirmwareUpgradeActivity.class, "type", "show_update_newVersion");
                        } else {
                            Intent_utils.enterIntentContext(this, FirmwareUpgradeActivity.class, "type", "show_update_newVersion");
                        }
                    }
                } else {
                    LogUtils.i("获取固件包 数据  失败");
                }


                break;

        }
    }

    public void mainHandleDeviceList() {
        Robot connect = AppContext.get().getCurrentDevice();
        removeFragmentFromManager();
        //设置主界面中间内容
        mainfragmentList = new ArrayList();
        mainAdapter = new MainAdapter(fm, mainfragmentList);
        binding.mMainViewPager.setAdapter(mainAdapter);
        String productId = connect.getProductId();
        Bundle bundleBase = new Bundle();
        if ("x5-max".equals(productId)) {
            bf = BaseStationFragment.newInstance(bundleBase);
            bf.setProductType(1);
            mainfragmentList.add(bf);

            Bundle bundle = new Bundle();
            mainFragment = MainFragment.newInstance(bundle);
            mainFragment.setProductType(0);
            mainfragmentList.add(mainFragment);
            //根据设备个数动态添加 小点点(多加一个)
            binding.pointLayoutl.initViews(2, 30, 20);
            binding.pointLayoutl.changePosition(0);//设置小点点选择
        } else {
            mainFragment = MainFragment.newInstance(bundleBase);
            mainFragment.setProductType(0);
            mainfragmentList.add(mainFragment);
        }
        mainAdapter.notifyDataSetChanged();
    }

    private void removeFragmentFromManager() {
        //LogUtils.ti("removeFragmentFromManager 移除 fragment 对象");
        if (mainfragmentList == null) {
            return;
        }
        //LogUtils.ti("Manager 移除 fragment 对象");
        FragmentTransaction transaction = fm.beginTransaction();
        for (int i = mainfragmentList.size() - 1; i >= 0; i--) {
            //LogUtils.ti(" 移除 fragment 对象");
            Fragment fragment = mainfragmentList.get(i);
            //然后从List中移除
            mainfragmentList.remove(fragment);
            //先从Transaction移除
            transaction.remove(fragment);
            transaction.detach(fragment);

        }
        transaction.commitNowAllowingStateLoss();
    }

    private void setCurrentPage(int currentItem) {
        // LogUtils.ti(" currentItem: " + currentItem);
        LogUtils.i(" currentItem: " + currentItem);
        binding.pointLayoutl.changePosition(currentItem);//设置小点点选择
    }

    public void setPageSelectStateChange(int currentSelected) {
        for (int i = 0; i < mainfragmentList.size(); i++) {
            LazyLoadFragment fragment = (LazyLoadFragment) mainfragmentList.get(i);
            if (fragment.isAdded()) {
                if (fragment.isPageSelected() && i != currentSelected) {
                    fragment.onPageUnselect(i);
                }
            }

        }
        LazyLoadFragment currentFragment = ((LazyLoadFragment) mainfragmentList.get(currentSelected));
        if (currentFragment.isAdded()) {
            currentFragment.onPageSelect(currentSelected);
        }
    }

    private JSONObject productConfig;

    /**
     * inxni 切换机器图片
     */
    public void switchRobotIcon(ImageView robotIconControl) {

        productConfig = AppContext.getConfig();
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentview = inflater.inflate(R.layout.layout_switch_robot_icon_popup, null);
        RadioGroup mRgSwitchRobotIconColor = contentview.findViewById(R.id.rg_mianSwitchRobotIconColor);
        RadioButton rb_white = contentview.findViewById(R.id.rb_mianSwitchRobotIcon_white);
        RadioButton rb_pink = contentview.findViewById(R.id.rb_mianSwitchRobotIcon_pink);
        RadioButton rb_blue = contentview.findViewById(R.id.rb_mianSwitchRobotIcon_purple);
        RadioButton rb_gray = contentview.findViewById(R.id.rb_mianSwitchRobotIcon_gray);
        try {
            JSONArray jsonArray = productConfig.getJSONArray(ProductConfigConstants.robotIconColorSpecies);
            LogUtils.i(jsonArray.length() + ">>>>>>>>>> " + new Gson().toJson(jsonArray));
            String json = new Gson().toJson(jsonArray);
            setVisibility(rb_white, json.contains(getString(R.string.H_RobotColor_1))); //白
            setVisibility(rb_pink, json.contains(getString(R.string.H_RobotColor_2)));  //粉
            setVisibility(rb_blue, json.contains(getString(R.string.H_RobotColor_3)));  //蓝
            setVisibility(rb_gray, json.contains(getString(R.string.H_RobotColor_4)));  //灰
        } catch (JSONException e) {
            e.printStackTrace();
        }

        switchRobotTextColor(rb_white, rb_pink, rb_blue, rb_gray);

        mRgSwitchRobotIconColor.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                String switch_icon = "white";
                switch (checkedId) {
                    case R.id.rb_mianSwitchRobotIcon_white:
                        switch_icon = "white";
                        robotIconControl.setImageResource(R.mipmap.main_x3_white_icon);
                        break;
                    case R.id.rb_mianSwitchRobotIcon_pink:
                        switch_icon = "pink";
                        robotIconControl.setImageResource(R.mipmap.main_x3_pink_icon);
                        break;
                    case R.id.rb_mianSwitchRobotIcon_purple:
                        switch_icon = "blue";
                        robotIconControl.setImageResource(R.mipmap.main_x3_purple_icon);
                        break;
                    case R.id.rb_mianSwitchRobotIcon_gray:
                        switch_icon = "gray";
                        robotIconControl.setImageResource(R.mipmap.main_x5_gray_icon);
                        break;
                }
                /**
                 * 切换机器人图片保存对应的key
                 */
                SharedPreferencesList.switchRobotPicture(MainActivity2.this, "switch", switch_icon, AppContext.get().getDeviceList(), "2222");
            }
        });
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        int width = (int) (wm.getDefaultDisplay().getWidth() * 0.9);
        //初始化PopupWindow对象
        popupWindow = new PopupWindow(contentview, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable());
        //让popupwindow在底部显示
        int position = binding.mMainViewPager.getCurrentItem();
        MainFragment current = (MainFragment) mainAdapter.getItem(position);
        popupWindow.showAsDropDown(current.ivSwitchRobotIcon);
    }

    /**
     * 默认选择机器图片颜色字体
     *
     * @param rb_white
     * @param rb_pink
     * @param rb_blue
     */
    private void switchRobotTextColor(RadioButton rb_white, RadioButton rb_pink, RadioButton rb_blue, RadioButton rb_gray) {
        SharedPreferences sp = getSharedPreferences("SP_ROBOT_ICON", MODE_PRIVATE);//创建sp对象,如果有key为"SP_PEOPLE"的sp就取出
        String peopleListJson = sp.getString("KEY_RobotIcon_LIST_DATA", "");  //取出key为"KEY_PEOPLE_DATA"的值，如果值为空，则将第二个参数作为默认值赋值
        if (peopleListJson != "")  //防空判断
        {
            Gson gson = new Gson();
            List<RobotIconColorBean> mList = gson.fromJson(peopleListJson, new TypeToken<List<RobotIconColorBean>>() {
            }.getType());//将json字符串转换成List集合
            if (mList.size() > 0) {
                String connect_deviceId = AppContext.get().getCurrentDevice().getDeviceId();
                for (int i = 0; i < mList.size(); i++) {
                    if (mList.get(i).getDeviceId().equals(connect_deviceId)) {
                        String color = mList.get(i).getIsICutoverColor();
                        if (color != null) {
                            switch (color) {
                                case "white":
                                    //白色
                                    rb_white.setChecked(true);
                                    break;
                                case "pink":
                                    //粉色
                                    rb_pink.setChecked(true);
                                    break;
                                case "blue":
                                    //蓝色
                                    rb_blue.setChecked(true);
                                    break;
                                case "gray":
                                    //灰色
                                    rb_gray.setChecked(true);
                                    break;
                            }
                        } else {
                            rb_gray.setChecked(true);
                        }
                    }
                }
            } else {
                rb_gray.setChecked(true);
            }
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        mVelocityTracker.addMovement(ev);
        mVelocityTracker.computeCurrentVelocity(2000);
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                ee1 = ev.getY();
                startX = (int) ev.getX();
//                Log.d(TAG, " : dispatchTouchEvent********** 按下 按下: ");
                break;
            case MotionEvent.ACTION_MOVE:
                ee2 = ev.getY();
                if (mainFragment.bottomLayoutView.mCbMainBottomUnfold.isChecked()) {
                    yVelocity = mVelocityTracker.getYVelocity();//速度
                    yVelocity = Math.abs(yVelocity);
                    if ((ee2 - ee1) / 2 > FLING_MIN_DISTANCE_TOUCH && (yVelocity / 2) > 1200) {
//                        Log.d(TAG, " : dispatchTouchEvent********** : ");
                        setBottomUiState("close", true, "555");

                        mainFragment.bottomLayoutView.mCbMainBottomUnfold.setChecked(false);
//                        binding.ivGreatManyIcon.setClickable(true);//主界面多设备图标点击事件
                    }
                }
                //判断滑动的位置
                if ((startX - ev.getX() > criticalValue)) {
                    //右滑动
                    if (Constants.isTouchRight) {
                        Constants.isTouchRight = false;
                        Constants.left_right = "right";
//                        Log.d(TAG, " : onTouchEvent********** 右滑动: ");
                    }
                } else if (((ev.getX() - startX) > criticalValue)) {
                    //左滑动
                    if (((ev.getX() - startX)) > 400) {
                        Constants.left_right = "left";
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
                Constants.isTouchLeft = true;
                Constants.isTouchRight = true;
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 底部UI布局是否展开关闭
     *
     * @param type
     * @param state
     * @param source
     */
    public void setBottomUiState(String type, boolean state, String source) {
        if (mainFragment.bottomLayoutView != null && mainFragment.bottomLayoutView.mMainButtonLayout != null) {
            if ("open".equals(type)) {
                int height = getWindowManager().getDefaultDisplay().getHeight();
                BottomSettingView.animateOpen(binding.mMainViewPager, mainFragment.bottomLayoutView, mainFragment.bottomLayoutView.mMainButtonLayout, (int) (height / 1.14),
                        mainFragment.rlBottomLayoutViewBg, mainFragment.bottomLayoutView.mCbMainBottomUnfold,
                        MainActivity2.this, binding.ivGreatManyIcon, binding.ivMainReturn, binding.ivRightMenu, source);
            } else {
                BottomSettingView.animateClose(binding.mMainViewPager, MainActivity2.this, mainFragment.bottomLayoutView, mainFragment.bottomLayoutView.mMainButtonLayout,
                        mainFragment.rlBottomLayoutViewBg, state, mainFragment.bottomLayoutView.mCbMainBottomUnfold, binding.ivGreatManyIcon, binding.ivMainReturn, binding.ivRightMenu, source);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1111) {
            Log.i(TAG, "MainActivity 地图管理-返回------------------------------ ------");
            //地图管理-返回
            Robot robot = (Robot) AppContext.get().getCurrentDevice();
            isShowMapRead(robot);
            mainFragment.bottomLayoutView.mStateMode = "";
            mainFragment.bottomLayoutView.selectMode();//动态更新上拉中模式是否选中
        }
//        else if (resultCode == 22) {
//            //重引导界面返回过来的
//            getLogoutToken();
//        }
    }

    /**
     * 检测地图小红点
     */
    public void isShowMapRead(Robot robot) {
        if (mainFragment.bottomLayoutView == null || mainFragment.bottomLayoutView.mIvMapManagerNotRead == null) {
            return;
        }

        boolean mapSaveNotRead = SharedPrefsUtil.getValue(MainActivity2.this, Constants.NOT_READ_TAG, Constants.KEY_MAP_SAVE_NOT_READ, true);
        boolean roomNotRead = SharedPrefsUtil.getValue(MainActivity2.this, Constants.NOT_READ_TAG, Constants.KEY_ROOM_EDIT_NOT_READ, true);
        boolean customNotRead = SharedPrefsUtil.getValue(MainActivity2.this, Constants.NOT_READ_TAG, Constants.KEY_CUSTOM_EDIT_NOT_READ, true);
        boolean restrictNotRead = SharedPrefsUtil.getValue(MainActivity2.this, Constants.NOT_READ_TAG, Constants.KEY_RESTRICT_EDIT_NOT_READ, true);

//        Log.i(TAG, "MainActivity isShowMapRead------------------------------ ------" + mapSaveNotRead + " : " + roomNotRead + " : " + restrictNotRead);
        if (mapSaveNotRead || roomNotRead || customNotRead || restrictNotRead) {
            //地图管理小红点
            mainFragment.bottomLayoutView.mIvMapManagerNotRead.setVisibility(View.VISIBLE);
        } else {
            mainFragment.bottomLayoutView.mIvMapManagerNotRead.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 固件新版本Dialog
     */
    public void newVersionsHintDialog(Context context, String content, String
            dialogTitle, String str1, String str2, String newVersion, String mUpgradeDesc) {
        if (firmware_dialog == null) {
            firmware_dialog = new Dialog(context);
        }
        if (firmware_dialog.isShowing()) {
            return;
        }
        firmware_dialog.setContentView(R.layout.outlogin_dialog);
        firmware_dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        firmware_dialog.setCanceledOnTouchOutside(false);
        TextView mBtnOutLoginConfirm = firmware_dialog.findViewById(R.id.btn_outLoginConfirm);
        TextView mBtnOutLoginCancel = firmware_dialog.findViewById(R.id.btn_outLoginCancel);
        TextView mTvDialogTitle = firmware_dialog.findViewById(R.id.tv_dialogTitle);
        TextView mContent = firmware_dialog.findViewById(R.id.tv_content);

        mTvDialogTitle.setText(dialogTitle);
        mContent.setText(content);

        mBtnOutLoginCancel.setText(str1);
        mBtnOutLoginConfirm.setText(str2);
        mBtnOutLoginConfirm.setTextColor(ContextCompat.getColor(this, R.color.button_color2));
        Robot robot = (Robot) AppContext.get().getCurrentDevice();

        mBtnOutLoginConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                JSONObject productConfig = AppContext.getConfig();
                if (!productConfig.optBoolean(ProductConfigConstants.canUpgradeFirmware)) {
                    ToastUtil.show(MainActivity2.this, getString(R.string.MO_T_Update_Err), Toast.LENGTH_SHORT);
                    return;
                }
//                Robot device = AppContext.get().getCurrentDevice();
//                if (device.getRobotStatus().getWorkState() != RobotStatus.STATE_CHARGING || device.getRobotStatus().getBattery() <= 20) {
//                    return;
//                }
                remindUpdate = true;
                robot.getFirmwareUpdateInfo().setCheck(true);//标记
                //开始升级
                DataParam param = new DataParam();
                param.setData_type("upgrade_package");
                param.setFile_name(robot.getFirmwareUpdateInfo().getFileName());
                AppContext.getProductService().getData(param);
                firmware_dialog.dismiss();
            }
        });
        mBtnOutLoginCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                robot.getFirmwareUpdateInfo().setCheck(true);//标记
                firmware_dialog.dismiss();
            }
        });
        if (!firmware_dialog.isShowing()) {
            firmware_dialog.show();
        }
    }


    /**
     * 注销账号 提示
     *
     * @param context
     * @param dialogTitle
     * @param content
     * @param str1
     */
    public void logoutHintDialog(Context context, String
            dialogTitle, String content, String str1) {
        if (dialog == null) {
            dialog = new Dialog(context);
            if (dialog.isShowing()) {
                return;
            }
            dialog.setContentView(R.layout.outlogin_dialog);
            dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
            dialog.setCanceledOnTouchOutside(false);
            TextView mBtnOutLoginConfirm = dialog.findViewById(R.id.btn_outLoginConfirm);
            TextView mBtnOutLoginCancel = dialog.findViewById(R.id.btn_outLoginCancel);
            TextView mTvDialogTitle = dialog.findViewById(R.id.tv_dialogTitle);
            TextView mContent = dialog.findViewById(R.id.tv_content);
            View main_view = dialog.findViewById(R.id.main_view);
            mBtnOutLoginCancel.setVisibility(View.GONE);
            main_view.setVisibility(View.GONE);

            mTvDialogTitle.setText(dialogTitle);
            mContent.setText(content);
            mBtnOutLoginConfirm.setText(str1);
            mBtnOutLoginConfirm.setTextColor(ContextCompat.getColor(this, R.color.button_color2));

            mBtnOutLoginConfirm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            mBtnOutLoginCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            if (!dialog.isShowing()) {
                dialog.show();
            }
        }
    }

    public void setFaultState(String errMsgByCode, int type, String laiyuan) {
        LogUtils.i(errMsgByCode + " :  ==4444:gggggb   vvvvvvvvvvvvvvvvvvvvvvvv : " + type + " , " + laiyuan);
        if (errMsgByCode.equals("恢复正常")) {
            for (int i = 0; i < mMesListData.size(); i++) {
                if (mMesListData.get(i).getType() == 2 || mMesListData.get(i).getType() == 3) {
                    mMesListData.remove(i);
                }
            }
            messageListIsShow(mMesListData);
        } else {
            MainMesListBean bean = new MainMesListBean();
            bean.setType(type);
            bean.setContent(errMsgByCode);
            if (mMesListData.size() > 0) {
                for (int i = 0; i < mMesListData.size(); i++) {
                    if (mMesListData.get(i).getType() == 2 || mMesListData.get(i).getType() == 3) {
                        mMesListData.remove(i);
                        mMesListData.add(bean);
                    } else {
                        mMesListData.add(bean);
                    }
                }
            } else {
                mMesListData.add(bean);
            }
            //     Log.d(TAG, "state ==4444:ffffffffffffffffffffffffffffff "+new Gson().toJson(mMesListData));
            Set set = new LinkedHashSet<MainMesListBean>();
            set.addAll(mMesListData);
            mMesListData.clear();
            mMesListData.addAll(set);
            // LogUtils.i(mMesListData.get(0).getContent() + " : activity.mMesListData   " + mMesListData.size());
            messageListIsShow(mMesListData);
        }
    }

    /**
     * 消息列表显示
     */
    public void messageListIsShow(List<MainMesListBean> msg) {
//        Log.d(TAG, "消息列表显示 " + msg.size());
        if (msg.size() > 0) {
            binding.mainMesList.setVisibility(View.VISIBLE);//消息列表
        } else {
            binding.mainMesList.setVisibility(View.GONE);//消息列表
        }
        mesAdapte.notifyDataSetChanged();
    }

    @Override
    protected void onPause() {
        super.onPause();
        remindUpdate = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        if (screenStatusReceiver != null) {
//            unregisterReceiver(screenStatusReceiver);
//        }
        if (runnable != null) {
            ThreadUtils.getInstance().removeThread(runnable);//关闭
        }
        if (EventBus.getDefault().isRegistered(this)) {
            LogUtils.i("onDestroy------------------------------ ------");
//            AppContext.get().setDeviceVariety("default");
            EventBus.getDefault().unregister(this);
        }
        if (myHandler != null) {
            //删除所有消息
            myHandler.removeCallbacksAndMessages(null);
        }
    }

    private void getDeviceStateAndMap() {
        Log.d("deviceState", "===== get deviceState ====");
        Robot device = AppContext.get().getCurrentDevice();
        if (device != null) {
            AppContext.getProductService().requestMap();
            AppContext.getProductService().getDeviceState();
            myHandler.removeMessages(MESSAGE_TYPE_REQUEST_MAP_AND_PATH);
            myHandler.sendEmptyMessageDelayed(MESSAGE_TYPE_REQUEST_MAP_AND_PATH, YuGongConstants.DURATION_REQUEST_DATA);
        }
    }

    private void sendAliveHeartBeat() {
        if (AppUtil.isRuning(this)) {
            AppContext.getProductService().sendAliveHeartbeat();
        }
        myHandler.removeMessages(MSG_KEEP_ALIVE);
        myHandler.sendEmptyMessageDelayed(MSG_KEEP_ALIVE, YuGongConstants.DURATION_KEEP_ALIVE);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //禁止划屏关闭界面
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            MyApplication.recvActive = false;
            AppContext.get().disconnectDevice();
            Intent_utils.backIntent(this, MainBottomTabActivity.class);
        }
        return super.onKeyDown(keyCode, event);
    }

    private static class MainFragmentHandler extends Handler {
        SoftReference<MainActivity2> softReference;

        public MainFragmentHandler(MainActivity2 activity) {
            softReference = new SoftReference<>(activity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (softReference.get() != null) {
                softReference.get().binding.mMainViewPager.setCurrentItem(msg.what, false);
                if (msg.what == 0) {
                    softReference.get().setCurrentPage(msg.what);
                    softReference.get().setPageSelectStateChange(msg.what);
                }

            }
        }
    }

    public static class MainHandler extends Handler {
        SoftReference<MainActivity2> mainActivity2SoftReference;

        public MainHandler(MainActivity2 activity) {
            mainActivity2SoftReference = new SoftReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Robot device = AppContext.get().getCurrentDevice();
            if (device != null) {
                if (msg.what == Event.MESSAGE_TYPE_REQUEST_MAP_AND_PATH) {
                    if (mainActivity2SoftReference.get() != null) {
                        mainActivity2SoftReference.get().getDeviceStateAndMap();
                    }
                } else if (msg.what == MSG_KEEP_ALIVE) {
                    if (mainActivity2SoftReference.get() != null) {
                        mainActivity2SoftReference.get().sendAliveHeartBeat();
                    }
                }
            }

        }
    }

    public void setVisibility(View view, boolean visibility) {
        view.setVisibility(visibility ? View.VISIBLE : View.GONE);
    }
}